package com.example.blog.controller;

import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.UserService;
import com.example.blog.utils.JwtUtil;
import com.example.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserController
 * Package: IntelliJ IDEA
 * Description:
 *
 * @Author 谷京京
 * @Create 2024/3/26 22:58
 * @Version 1.0
 */
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/login")
    public Result login(String username, String password) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        //获取数据库中的密码
        UserInfo userInfo = userService.queryByName(username);
        if(userInfo == null || userInfo.getId() < 0) {
            return Result.fail("用户不存在");
        }
//        if(!password.equals(userInfo.getPassword())) {
//            return Result.fail("密码错误");
//        }
        if (!SecurityUtils.verify(password, userInfo.getPassword())) {
            return Result.fail("密码错误");
        }
        //生成token并返回
        Map<String, Object> claim = new HashMap<>();
        claim.put("id", userInfo.getId());
        claim.put("name", userInfo.getUsername());
        String token = JwtUtil.genToken(claim);
        return Result.success(token);
    }
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        //从token中获取用户ID
        String token = request.getHeader("user_token");
        Integer userId = JwtUtil.getUserIdFromToken(token);
        if(userId == null) {
            return null;
        }
        return userService.queryById(userId);
    }
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer id) {
        if(id == null || id < 0) {
            return null;
        }
        return userService.getAuthorInfo(id);
    }
}
